Given a multi-dimensional array arr and a depth n, return a flattened version of that array.
A multi-dimensional array is a recursive data structure that contains integers or other multi-dimensional arrays.
A flattened array is a version of that array with some or all of the sub-arrays removed and replaced with the actual elements in that sub-array. This flattening operation should only be done if the current depth of nesting is less than n. The depth of the elements in the first array are considered to be 0.
Please solve it without the built-in Array.flat method.
var flat = function (arr, n) {
};
Example 1:
Input
arr = [1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]]
n = 0
Output
[1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]]
Example 2:
Input
arr = [1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]]
n = 1
Output
[1, 2, 3, 4, 5, 6, 7, 8, [9, 10, 11], 12, 13, 14, 15]
Example 3:
Input
arr = [[1, 2, 3], [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]]
n = 2
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
意外地突然來一題很簡單的,其實以 example 的內容,好像不需要判斷 小於 0,可以一行解。不過兩個都做了。
網友的反而很複雜。
有 if,但 runtime 較快:
var flat = function (arr, n) {
if (n <= 0) {
return arr;
}
return arr.flat(n)
};
// Runtime 99ms
// Beats 71.72%of users with JavaScript
// Memory 60.92MB
// Beats 91.83%of users with JavaScript
沒有 if,但 runtime 較慢:
var flat = function (arr, n) {
return arr.flat(n)
};
// Runtime 107ms
// Beats 67.09%of users with JavaScript
// Memory 60.94MB
// Beats 91.83%of users with JavaScript
其他網友解,其實我有點不理解為什麼大家要這麼複雜,打算問人。
var flat = function (arr, n) {
const res = [];
function helper(arr,depth) {
for(const val of arr) {
if(typeof(val) === 'object' && depth < n) {
helper(val,depth + 1);
} else {
res.push(val);
}
}
return res;
}
return helper(arr,0);
};
// Runtime 89ms
// Beats 81.82%of users with JavaScript
// Memory 62.14MB
// Beats 77.71%of users with JavaScript